import { useEffect, useState, useRef } from 'react';
import { InputNumber, message } from 'antd';
import {
  ProFormText,
  ModalForm,
  ProFormDigit,
  ProFormRadio,
  ProFormCheckbox,
} from '@ant-design/pro-components';
import styles from './index.module.less';
import {
  chengFa,
  chuFa,
  getShouYiLvByPrice,
  isLocal,
  isSuccess,
  jiaFa,
  jingDuSum,
  orderText,
  zhiYingSunTriggerPrice,
} from '@/utils';
import { priceTypeOptions } from '@/utils/helper';
import { delZhiYingApi, feiLvApi, getZhiYingSunApi, zhiYingSunApi } from '@/api';
import { Desc } from './ZhiYingSunCpn';
import { ShouYiLvSlider } from './CommonCpn';

export default function ZhiYingModal({ open, setOpen, formData, reload, contractList }: any) {
  const shouYiLv = isLocal() ? 0 : 0;
  const formRef: any = useRef('');
  const [zhiYingData, setZhiYingData] = useState<any>(null);
  const [zhiSunData, setZhiSunData] = useState<any>(null);
  const [showZhiYing, setShowZhiYing] = useState(false);
  const [showZhiSun, setShowZhiSun] = useState(false);
  const [zhiYingShouYiLv, setZhiYingShouYiLv] = useState(shouYiLv);
  const [zhiSunShouYiLv, setZhiSunShouYiLv] = useState(shouYiLv);
  const [shouXuFeiLv, setShouXuFeiLv] = useState(0); // 手续费率

  // 止盈触发价
  useEffect(() => {
    const zhengFu = formData?.newSize * 1 > 0 ? 1 : -1; // 正负
    const shouYiLv = chuFa(zhiYingShouYiLv, 100) * zhengFu;
    const price = zhiYingSunTriggerPrice(shouYiLv, formData, shouXuFeiLv);
    formRef?.current?.setFieldsValue({ zhiYingPrice: price });
  }, [zhiYingShouYiLv, shouXuFeiLv]);

  // 止损触发价
  useEffect(() => {
    const zhengFu = formData?.newSize * -1 > 0 ? 1 : -1; // 正负
    const shouYiLv = chuFa(zhiSunShouYiLv, 100) * zhengFu;
    const price = zhiYingSunTriggerPrice(shouYiLv, formData, shouXuFeiLv);
    formRef?.current?.setFieldsValue({ zhiSunPrice: price });
  }, [zhiSunShouYiLv, shouXuFeiLv]);

  useEffect(() => {
    console.log('formData: ', formData);
    init();
    getFeiLv();
  }, [open]);

  // 初始化设置
  function init() {
    const type = 0;
    formRef?.current?.setFieldsValue({
      zhiYingPriceType: type,
      zhiYingWeiTuo: 'gtc',
      zhiSunPriceType: type,
    });
    initYingSun();
  }

  // 提交
  const submit = async () => {
    if (!showZhiYing && !showZhiSun) {
      setOpen(false);
      return;
    }
    let value = await formRef?.current?.validateFieldsReturnFormatValue();
    // console.log('格式化后的表单数据: ', value);
    // 处理提交参数
    const { zhiYingparams, zhiSunparams } = handleZhiYingParams(value);
    console.log('zhiYingparams, zhiSunparams: ', zhiYingparams, zhiSunparams);
    // 处理删除逻辑
    const delres = await deleteZhiYingSunRes();
    console.log('1.delres: ', delres);
    if (!delres) return;
    // 处理添加逻辑
    let zhiYingRes = true;
    let zhiSunRes = true;
    if (showZhiYing) zhiYingRes = await handleZhiYingApi(zhiYingparams);
    if (showZhiSun) zhiSunRes = await handleZhiYingApi(zhiSunparams);
    if (zhiYingRes && zhiSunRes) message.success('成功');
    reload();
    setOpen(false);
  };

  // 止盈止损
  async function handleZhiYingApi(params: any) {
    const res: any = await zhiYingSunApi(params);
    console.log('res:止盈止损 ', res);
    if (!isSuccess(res, false)) {
      const msg = res?.msg;
      if (msg.includes('Trigger.Price must > last_price')) {
        message.error('止盈触发价必须大于最新价');
      } else {
        message.error(res.msg);
      }
      return false;
    }
    return true;
  }

  // 处理提交的参数
  function handleZhiYingParams(value: any) {
    const commonInitial = {
      contract: formData.contract,
      close: true, // 设置为 true 的时候执行平仓操作
      size: 0, // 平仓操作必须为0
      text: orderText,
      price: '0',
      tif: 'ioc',
    };
    const strategy_type = 0; //  触发策略,只能用0
    const order_type = formData?.size > 0 ? 'close-long-position' : 'close-short-position';
    // 止盈
    const zhiYingparams: any = {
      initial: { ...commonInitial },
      trigger: {
        strategy_type, //  触发策略,只能用0
        price_type: value?.zhiYingPriceType, // 参考价格类型。 0 - 最新成交价，1 - 标记价格，2 - 指数价格
        price: value?.zhiYingPrice + '', // 价格触发时为价格，价差触发时为价差
        rule: formData?.newSize > 0 ? 1 : 2, // 价格条件类型 1 - 大于等于，2 - 小于等于；止盈为1，止损为2；注意空单取反
      },
      order_type,
    };
    // 止损
    const zhiSunparams = {
      initial: {
        ...commonInitial,
        tif: 'ioc',
      },
      trigger: {
        strategy_type, //  触发策略,只能用0
        price_type: value?.zhiSunPriceType, // 参考价格类型。 0 - 最新成交价，1 - 标记价格，2 - 指数价格
        price: value?.zhiSunPrice + '', // 价格触发时为价格，价差触发时为价差
        rule: formData?.newSize > 0 ? 2 : 1, // 价格条件类型 1 - 大于等于，2 - 小于等于；止盈为1，止损为2；注意空单取反
      },
      order_type,
    };
    return { zhiYingparams, zhiSunparams };
  }

  // 处理删除逻辑
  async function deleteZhiYingSunRes() {
    if (zhiYingData) {
      const res = await delZhiYingApi({ order_id: zhiYingData?.id_string });
      if (!isSuccess(res)) return false;
    }
    if (zhiSunData) {
      const res = await delZhiYingApi({ order_id: zhiSunData?.id_string });
      if (!isSuccess(res)) return false;
    }
    return true;
  }

  // 初始化处理止盈止损
  function initYingSun() {
    const ying = formData?.zhiYingSunData?.quanCang?.zhiYing;
    const sun = formData?.zhiYingSunData?.quanCang?.zhiSun;
    if (ying) {
      console.log('有ying', ying, ying?.trigger?.price);
      const _shouYiLv = getShouYiLvByPrice(+ying.trigger?.price, formData, shouXuFeiLv);
      console.log('==== start,止盈收益率: ', _shouYiLv);
      setZhiYingShouYiLv(_shouYiLv);
      setZhiYingData(ying);
      setShowZhiYing(true);
      formRef?.current?.setFieldsValue({
        isZhiYing: [true],
        zhiYingPriceType: ying?.trigger?.price_type,
        zhiYingPrice: Number(ying?.trigger?.price),
      });
    }
    if (sun) {
      setZhiSunData(sun);
      setShowZhiSun(true);
      console.log('有sun', sun, sun?.trigger?.price);
      const _shouYiLv = getShouYiLvByPrice(+sun.trigger?.price, formData, shouXuFeiLv);
      console.log('止损收益率: ', _shouYiLv);
      setZhiSunShouYiLv(_shouYiLv);
      formRef?.current?.setFieldsValue({
        isZhiSun: [true],
        zhiSunPriceType: sun?.trigger?.price_type,
        zhiSunPrice: Number(sun?.trigger?.price),
      });
    }
  }

  function onValuesChange(e: any) {
    if (e?.isZhiYing) setShowZhiYing(e?.isZhiYing?.length > 0);
    if (e?.isZhiSun) setShowZhiSun(e?.isZhiSun?.length > 0);
  }

  // 个人交易费率
  async function getFeiLv() {
    const res: any = (await feiLvApi())?.data;
    setShouXuFeiLv(+res?.futures_maker_fee);
  }

  return (
    <ModalForm
      title="止盈/止损"
      formRef={formRef}
      open={open}
      layout="horizontal"
      onFinish={submit}
      onOpenChange={setOpen}
      labelCol={{ span: 7 }}
      width={600}
      onValuesChange={onValuesChange}
      modalProps={{ maskClosable: false }}
    >
      <div className={`${styles.ZhiYingModal}`}>
        <Desc formData={formData} contractList={contractList} />
        <div className={`${styles.tmodal}`}>
          <div className={`${styles.titlerow}`}>
            <ProFormCheckbox.Group name="isZhiYing" options={[{ label: '止盈', value: true }]} />
          </div>
          <div className={`${styles.trow} ${showZhiYing && styles.trowShow}`}>
            <div className={`${styles.ttop}`}>
              <div className={`${styles.name}`}>止盈触发价(USDT)</div>
              <div className={`${styles.topt}`}>
                <ProFormRadio.Group name="zhiYingPriceType" options={priceTypeOptions} />
              </div>
            </div>
            <ProFormDigit name="zhiYingPrice" style={{ width: '100%' }} />
            <ShouYiLvSlider shouYiLv={zhiYingShouYiLv} changeShouYiLv={setZhiYingShouYiLv} />
          </div>
        </div>
        <div className={`${styles.tmodal}`}>
          <div className={`${styles.titlerow}`}>
            <ProFormCheckbox.Group name="isZhiSun" options={[{ label: '止损', value: true }]} />
          </div>
          <div className={`${styles.trow} ${showZhiSun && styles.trowShow}`}>
            <div className={`${styles.ttop}`}>
              <div className={`${styles.name}`}>止损触发价(USDT)</div>
              <div className={`${styles.topt}`}>
                <ProFormRadio.Group name="zhiSunPriceType" options={priceTypeOptions} />
              </div>
            </div>
            <ProFormDigit name="zhiSunPrice" style={{ width: '100%' }} />
            <ShouYiLvSlider shouYiLv={zhiSunShouYiLv} changeShouYiLv={setZhiSunShouYiLv} />
          </div>
        </div>
      </div>
      <div className={`${styles.xxx}`}></div>
    </ModalForm>
  );
}
